﻿using Microsoft.Extensions.DependencyInjection;
using MudBlazor;
using MXERP.Infrastructure.Managers;
using System.Net.Http.Headers;

namespace MXERP.Infrastructure.Authentication
{
    public class CustomDelegatingHandler : DelegatingHandler
    {
        private readonly ILocalStorageService _localStorageService;
        private readonly IServiceProvider _provider;
        private readonly ISnackbar _snackbar;

        public CustomDelegatingHandler(IServiceProvider serviceProvider)
        {
            _provider = serviceProvider.CreateScope().ServiceProvider;
            _localStorageService = _provider.GetRequiredService<ILocalStorageService>();
            _snackbar = _provider.GetRequiredService<ISnackbar>();
            //_signEntryManager = provider.GetRequiredService<ISignEntryManager>();
        }

        // 请求前拦截
        protected async Task<HttpRequestMessage> InterceptRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var token = await _localStorageService.GetItemAsync<string>(StorageConstant.Local.AuthToken, cancellationToken);
            if (!string.IsNullOrWhiteSpace(token))
            {
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
            }
            return request;
        }

        // 响应后拦截
        protected async Task<HttpResponseMessage> InterceptResponseAsync(HttpRequestMessage request, HttpResponseMessage response, CancellationToken cancellationToken)
        {
            switch (response.StatusCode)
            {
                case System.Net.HttpStatusCode.OK:
                    if (response.Content.Headers.ContentType?.MediaType == "application/octet-stream")
                    {
                        return response;
                    }
                    var result = await response.ToResult();
                    if (result.Status == 200)
                    {
                        return response;
                    }
                    else if (result.Status == 100)
                    {

                    }
                    else
                    {
                        ErrorHandle(result.Status, result.Message ?? "");
                    }
                    break;
                //case System.Net.HttpStatusCode.BadRequest:
                //    _snackbar.Add("错误请求(400)", Severity.Error);
                //    break;
                case System.Net.HttpStatusCode.Unauthorized:
                    _snackbar.Add("登录已失效，请重新登录(401)");
                    var signEntryManager = _provider.GetRequiredService<ISignEntryManager>();
                    await signEntryManager.RefreshToken();
                    return await SendAsync(request, cancellationToken);
                    //case System.Net.HttpStatusCode.Forbidden:
                    //    _snackbar.Add("拒绝访问(403)", Severity.Error);
                    //    break;
                    //case System.Net.HttpStatusCode.NotFound:
                    //    _snackbar.Add("请求错误,未找到该资源(404)", Severity.Error);
                    //    break;
                    //case System.Net.HttpStatusCode.MethodNotAllowed:
                    //    _snackbar.Add("请求方法未允许(405)", Severity.Error);
                    //    break;
                    //case System.Net.HttpStatusCode.RequestTimeout:
                    //    _snackbar.Add("请求超时(408)", Severity.Error);
                    //    break;
                    //case System.Net.HttpStatusCode.InternalServerError:
                    //    _snackbar.Add("服务器端出错(500)", Severity.Error);
                    //    break;
                    //case System.Net.HttpStatusCode.NotImplemented:
                    //    _snackbar.Add("网络未实现(501)", Severity.Error);
                    //    break;
                    //case System.Net.HttpStatusCode.BadGateway:
                    //    _snackbar.Add("网络错误(502)", Severity.Error);
                    //    break;
                    //case System.Net.HttpStatusCode.ServiceUnavailable:
                    //    _snackbar.Add("服务不可用(503)", Severity.Error);
                    //    break;
                    //case System.Net.HttpStatusCode.GatewayTimeout:
                    //    _snackbar.Add("网络超时(504)", Severity.Error);
                    //    break;
                    //case System.Net.HttpStatusCode.HttpVersionNotSupported:
                    //    _snackbar.Add("http版本不支持该请求(505)", Severity.Error);
                    //    break;
                    //default:
                    //    _snackbar.Add($"连接错误{response.StatusCode}", Severity.Error);
                    //    break;
            }
            return response;
        }

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var interceptedRequest = await InterceptRequestAsync(request, cancellationToken);
            HttpResponseMessage? response = null;
            try
            {
                response = await base.SendAsync(interceptedRequest, cancellationToken);
                //response.EnsureSuccessStatusCode();
            }
            catch (OperationCanceledException ex) when (!cancellationToken.IsCancellationRequested)
            {
                // 如果超时发生
                throw new TimeoutException("The request timed out.");
            }
            catch (Exception ex)
            {
                throw; // 其他异常保持原样抛出
            }
            return await InterceptResponseAsync(interceptedRequest, response, cancellationToken);
        }

        private void ErrorHandle(int status, string message)
        {
            switch (status)
            {
                case 1:
                    _snackbar.Add("token无效");
                    break;
                case 2:
                    _snackbar.Add("token过期");
                    //toSignIn();
                    break;
                case 401:
                    _snackbar.Add("权限不足,请联系管理员");
                    break;
                case 403:
                    _snackbar.Add("403");
                    break;
                case 98:
                    _snackbar.Add(message);
                    break;
                case 99:
                    _snackbar.Add("系统异常");
                    break;
                default:
                    _snackbar.Add(message);
                    break;
            }
        }
    }
}